package com.zhang.zhangapp.application;

import android.Manifest;
import android.app.Application;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.ImageView;


import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.view.CropImageView;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zaaach.citypicker.model.LocateState;
import com.zhang.zhangapp.R;
import com.zhang.zhangapp.base.Constant;
import com.zhang.zhangapp.base.config.BuildConfig;
import com.zhang.zhangapp.bean.shop.ShopType;
import com.zhang.zhangapp.bean.user.User;
import com.zhang.zhangapp.bean.user.UserDao;
import com.zhang.zhangapp.utils.PicassoImageLoader;

import org.xutils.DbManager;
import org.xutils.db.table.TableEntity;
import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.io.File;
import java.util.ArrayList;


/**
 * Created by 罗肖 on 2017/6/28.
 */
public class MApplication extends Application {

    private static MApplication instance;

    public static MApplication getInstance() {
        return instance;
    }

    private String token = "";

    private User user;

    DbManager.DaoConfig daoConfig;
    DbManager db;

    ImageOptions imageOptions;

    public DbManager.DaoConfig getDaoConfig() {
        return daoConfig;
    }

    public ImageOptions getImageOptions() {
        return imageOptions;
    }

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;


    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;

    private ArrayList<ShopType> shopTypeArrayList;

    private AMapLocation mapLocation;

    public AMapLocation getMapLocation() {
        return mapLocation;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        this.instance = this;
        x.Ext.init(this);
        x.Ext.setDebug(BuildConfig.DEBUG);
        initImageOptions();
        initWxSdk();

//        JPushInterface.setDebugMode(true);
//        JPushInterface.init(this);
    }

    private void initWxSdk() {

    }

    public ArrayList<ShopType> getShopTypeArrayList() {
        return shopTypeArrayList;
    }

    public void setShopTypeArrayList(ArrayList<ShopType> shopTypeArrayList) {
        this.shopTypeArrayList = shopTypeArrayList;
    }

    public User getUser() {
        if (user == null) {
            try {
                user = UserDao.getInstance().queryUser();
            } catch (Exception e) {
                Log.e("getUserError", e.getMessage());
            }
        }
        return user;
    }

    public String getToken() {
        if (token == null || token.length() == 0) {
            if (getUser() != null)
                token = getUser().getToken();
            else token = "";
        }
        return token;
    }

    private void setToken(String token) {
        this.token = token;
    }

    public void initImageOptions() {
        imageOptions = new ImageOptions.Builder()
                .setImageScaleType(ImageView.ScaleType.CENTER_CROP)
                .setIgnoreGif(false)
                .setCrop(true)//是否对图片进行裁剪
                .setFailureDrawableId(R.mipmap.test)
                .setLoadingDrawableId(R.mipmap.test)
                .build();
    }


    public void initLocation() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //获取一次定位结果：
        //该方法默认为false。
        mLocationOption.setOnceLocation(true);
        //获取最近3s内精度最高的一次定位结果：
        //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        mLocationOption.setOnceLocationLatest(true);
        //设置定位间隔,单位毫秒,默认为2000ms，最低1000ms。
        mLocationOption.setInterval(1000);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
        mLocationOption.setHttpTimeOut(20000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    public void initDB() {

        /**
         * 初始化DaoConfig配置
         */
        daoConfig = new DbManager.DaoConfig()
                //设置数据库名，默认xutils.db
                .setDbName("zhangApp.db")
                //设置数据库路径，默认存储在app的私有目录
                .setDbDir(new File(Environment.getExternalStorageDirectory().getPath() + "/zhangapp"))
                //设置数据库的版本号
                .setDbVersion(3)
                //设置数据库打开的监听
                .setDbOpenListener(new DbManager.DbOpenListener() {
                    @Override
                    public void onDbOpened(DbManager db) {
                        //开启数据库支持多线程操作，提升性能，对写入加速提升巨大
                        db.getDatabase().enableWriteAheadLogging();
                    }
                })
                //设置数据库更新的监听
                .setDbUpgradeListener(new DbManager.DbUpgradeListener() {
                    @Override
                    public void onUpgrade(DbManager db, int oldVersion, int newVersion) {
                    }
                })
                //设置表创建的监听
                .setTableCreateListener(new DbManager.TableCreateListener() {
                    @Override
                    public void onTableCreated(DbManager db, TableEntity<?> table) {
                        Log.i("JAVA", "onTableCreated：" + table.getName());
                    }
                });
        //设置是否允许事务，默认true
        //.setAllowTransaction(true)
        db = x.getDb(daoConfig);
    }


    public void setUser(User user, String token, String ticket) {
        this.user = user;
        user.setToken(token);
        user.setTickets(ticket);
        setToken(token);
        try {
            UserDao.getInstance().save(user);
        } catch (Exception e) {
            Log.e("saveUserError", e.getMessage());
        }
    }

    public void setUser(User user) {
        this.user = user;
        user.setToken(this.token);
        try {
            UserDao.getInstance().save(user);
        } catch (Exception e) {
            Log.e("saveUserError", e.getMessage());
        }
    }

    public void loginOut() {
        try {
            UserDao.getInstance().clearUser(user.getId());
        } catch (Exception e) {
        }
        this.user = null;
        this.token = null;

    }

    public void stopLocation() {
        if (mLocationClient != null) {
            mLocationClient.stopLocation();//停止定位后，本地定位服务并不会被销毁
            mLocationClient.onDestroy();//销毁定位客户端，同时销毁本地定位服务。
        }
    }

    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    mapLocation = amapLocation;
                    // cityPickerFragment.updateLocateState(LocateState.SUCCESS, amapLocation.getCity().replaceAll("市", ""));
                    //可在其中解析amapLocation获取相应内容。
                } else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }
        }
    };

}
